import { LineChart } from 'echarts/charts';
import {
  GridComponent,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { useEffect, useRef } from 'react';

import useWindowWidth from '@/hooks/event/use-window-width';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
]);

interface ChartData {
  date: string;
  questionCount: number;
  sessionCount: number;
  averageDelay?: number;
}

interface Props {
  height?: number;
  data: ChartData[];
  isShowDialog?: boolean;
}

const SmoothLineChart = ({ height = 300, data, isShowDialog = true }: Props) => {
  const chartRef = useRef(null);
  const { isPc } = useWindowWidth();

  useEffect(
    function setupChart() {
      if (!chartRef.current || !data.length) return;

      const chart = echarts.init(chartRef.current);

      // 根据设备类型格式化 X 轴标签：移动端去掉年份，避免拥挤
      const dates = isPc
        ? data.map((item) => item.date)
        : data.map((item) => (item.date && item.date.length >= 7 ? item.date.slice(5) : item.date));

      const maxCount = Math.max(...data.map((item) => item.questionCount + item.sessionCount));
      const yAxisMax = maxCount > 0 ? Math.ceil(maxCount * 1) + 1 : 1;

      let option;
      if (isShowDialog) {
        option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            borderWidth: 1,

            axisPointer: {
              type: 'line',
              lineStyle: {
                color: 'rgba(24, 144, 255, 0.3)',
                width: 2,
              },
            },
            backgroundColor: 'rgba(255, 255, 255, 0.6)',
            borderColor: 'rgba(255, 255, 255, 0.6)',
            borderRadius: 8,
            textStyle: {
              color: '#333',
            },
            extraCssText:
              'backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(10px); box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);',

            formatter: (params: any) => {
              const { dataIndex } = params[0];
              const item = data[dataIndex];
              return `
               <div style="padding:4px;border-radius: 6px;width:160px;">
                <div style="color:'#87919B'; margin-bottom: 5px;border-bottom: 1px solid #F2F3F3; padding-bottom: 10px;">${
                  item.date
                }</div>

                  <div style="display: flex;align-items: center;justify-content: space-between; margin-bottom: 5px;;">
                  <div style="display: flex;align-items: center;">
                    <div style="width:10px; height: 10px; background: #2171FA;margin-right: 8px;"></div>
                    <span style="color: #20242A; font-weight: bold;">对话数</span>
                  </div>
                    <b>${item.questionCount || 0}</b>
                  </div>
                  <div style="display: flex;align-items: center;justify-content: space-between; margin-bottom: 5px;;">
                  <div style="display: flex;align-items: center;">
                    <div style="width:10px; height: 10px; background: #0AC477;margin-right: 8px;"></div>
                    <span style="color: #20242A; font-weight: bold;">会话数</span>
                  </div>
                    <b>${item.sessionCount || 0}</b>
                  </div>
              </div>
            `;
            },
          },
          legend: {
            left: 15,
            top: 0,
            icon: 'roundRect',
            itemWidth: 14,
            itemHeight: 14,
            itemStyle: {
              borderRadius: 16,
            },
            itemGap: 15,
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '0%',
            top: 40,
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            // 关键修改1: 两边留空
            boundaryGap: false, // 从false改为true

            data: dates,
            axisLine: {
              lineStyle: {
                color: '#ccc',
              },
            },
            axisLabel: {
              color: '#87919D',
              fontSize: 12,
              interval: data.length > 15 ? 2 : 0,
            },
          },
          yAxis: {
            type: 'value',
            nameTextStyle: {
              color: '#666',
              fontSize: 12,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              color: '#87919D',
              margin: 12,
            },
            splitLine: {
              lineStyle: {
                color: ['#eee'],
                type: 'dashed',
              },
            },
            max: yAxisMax,
          },
          series: [
            {
              name: '对话数',
              type: 'line',
              data: data.map((item) => item.questionCount),
              smooth: true,
              symbol: 'none',
              lineStyle: {
                width: 3,
                color: '#1E6FFA',
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
                  { offset: 1, color: 'rgba(24, 144, 255, 0.05)' },
                ]),
              },
              itemStyle: {
                color: '#1E6FFA',
              },
            },
            {
              name: '会话数',
              type: 'line',
              data: data.map((item) => item.sessionCount),
              smooth: true,
              symbol: 'none',
              lineStyle: {
                width: 3,
                color: '#07C375',
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(82, 196, 26, 0.3)' },
                  { offset: 1, color: 'rgba(82, 196, 26, 0.05)' },
                ]),
              },
              itemStyle: {
                color: '#07C375',
              },
            },
          ],
        };
      } else {
        option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            backgroundColor: '#fff',
            borderWidth: 1,
            textStyle: {
              color: '#1D2129',
              fontSize: 12,
            },
            axisPointer: {
              type: 'line',
              lineStyle: {
                color: 'rgba(24, 144, 255, 0.3)',
                width: 2,
              },
            },
            formatter: (params: any) => {
              const { dataIndex } = params[0];
              const item = data[dataIndex];
              return `
               <div style="padding:4px;width:160px;">
              <div style="color:'#87919D'; margin-bottom: 5px;border-bottom: 1px solid #f0f0f0; padding-bottom: 10px;">${
                item.date
              }</div>

                <div style="display: flex;align-items: center;justify-content: space-between; margin-bottom: 5px;;">
                 <div style="display: flex;align-items: center;">
                  <div style="width:10px; height: 10px; background: #722ED1;margin-right: 8px;"></div>
                  <span style="color: #20242A; font-weight: bold;">平均时延</span>
                 </div>
                  <b>${item.averageDelay || 0}</b>
                </div>

              </div>
            `;
            },
          },
          legend: {
            left: 15,
            top: 0,
            icon: 'roundRect',
            itemWidth: 14,
            itemHeight: 14,
            itemStyle: {
              borderRadius: 16,
            },
            itemGap: 15,
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '0%',
            top: 40,
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            // 关键修改3: 两边留空
            boundaryGap: false, // 从false改为true
            data: dates,
            axisLine: {
              lineStyle: {
                color: '#ccc',
              },
            },
            axisLabel: {
              color: '#666',
              fontSize: 12,
              interval: data.length > 15 ? 2 : 0,
            },
          },
          yAxis: {
            type: 'value',
            name: '',
            nameTextStyle: {
              color: '#666',
              fontSize: 12,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              color: '#666',
              margin: 10,
            },
            splitLine: {
              lineStyle: {
                color: ['#eee'],
                type: 'dashed',
              },
            },
          },
          series: [
            {
              name: '首字延时',
              type: 'line',
              data: data.map((item) => item.averageDelay),
              smooth: true,
              symbol: 'none',
              lineStyle: {
                width: 3,
                color: '#722ED1',
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(114, 46, 209, 0.3)' },
                  { offset: 1, color: 'rgba(114, 46, 209, 0.05)' },
                ]),
              },
              itemStyle: {
                color: '#722ED1',
              },
            },
          ],
        };
      }

      chart.setOption(option);

      const handleResize = () => chart.resize();
      window.addEventListener('resize', handleResize);

      return function cleanup() {
        window.removeEventListener('resize', handleResize);
        chart.dispose();
      };
    },
    [data, isShowDialog, isPc],
  );

  return (
    <div style={{ width: '100%', height: `${height}px` }}>
      <div ref={chartRef} style={{ width: '100%', height: '100%' }} />
    </div>
  );
};

export default SmoothLineChart;
